package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Fans;
import com.xindaoapp.happypet.bean.Fans.Fan;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class MenuAttention extends UMBaseActivity implements OnClickListener {
    @ViewInject(R.id.tittle_common_cancel)
    private ImageView tittle_common_cancel;
    @ViewInject(R.id.tittle_common_content)
    private TextView tittle_common_content;

    @ViewInject(R.id.list)
    private PullToRefreshListView list;
    @ViewInject(R.id.loading)
    private FrameLayout loading;
    @ViewInject(R.id.noresult)
    private RelativeLayout noresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menuattention);
        ViewUtils.inject(this);
        setClick();
        initAttention(page);
    }

    private void setClick() {
        tittle_common_content.setText("关注");
        tittle_common_cancel.setOnClickListener(this);
        list.setPullRefreshEnabled(true);
        list.setScrollLoadEnabled(true);
        list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                fans.clear();
                page = 1;
                initAttention(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                initAttention(page);
            }
        });
        list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Intent intent = new Intent(MenuAttention.this, OtherActivity.class);
                // intent.putExtra("uid", fans.get(position).followuid);
                // intent.putExtra("name", fans.get(position).fusername);
                // intent.putExtra("face", fans.get(position).userface);
                // startActivity(intent);

                Intent intent = new Intent(MenuAttention.this, MainActivity.class);
                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        UserInfoFragment.class.getCanonicalName());
                Bundle bundle = new Bundle();
                bundle.putString(Constants.KEY_UID, fans.get(position).followuid);
                bundle.putString(Constants.KEY_USERNAME, fans.get(position).fusername);
                bundle.putString(Constants.KEY_USERFACE, fans.get(position).userface);
                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                MenuAttention.this.startActivity(intent);

            }
        });

    }

    private final List<Fan> fans = new ArrayList<Fan>();
    private Adapter adapter;

    private void initAttention(int page2) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page2));
        params.put("uid", UserState.getUserUid());
        params.put("pagesize", "15");
        AddClient.get(Address.FANSGUANZHU, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                Fans parse = JSON.parseObject(content, Fans.class);
                if (loading.getVisibility() == View.VISIBLE) {
                    loading.setVisibility(View.GONE);
                }
                try {
                    if (parse.getResult().equals("0")) {
                        if (Integer.parseInt(parse.getTotal()) == 0) {
                            noresult.setVisibility(View.VISIBLE);
                            list.setVisibility(View.GONE);
                        } else {
                            List<Fan> array = parse.array;
                            if (array.size() > 0) {
                                fans.addAll(array);
                            }
                            if (adapter == null) {
                                adapter = new Adapter(fans);
                                list.getRefreshableView().setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            if (Integer.parseInt(parse.getTotal()) < 10) {
                                list.setPullRefreshEnabled(false);
                                list.setScrollLoadEnabled(false);
                            }
                        }
                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    private void onLoaded() {
        list.onPullDownRefreshComplete();
        list.onPullUpRefreshComplete();
    }

    private class Adapter extends BaseAdapter {
        private final List<Fan> fan;

        public Adapter(List<Fan> fan) {
            super();
            this.fan = fan;
        }

        @Override
        public int getCount() {
            return fan.size();
        }

        @Override
        public Object getItem(int position) {
            return fan.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.fans_list_item, null);
                holder.face = (CircleImageView) convertView.findViewById(R.id.face);
                holder.iv_guanzhu = (ImageView) convertView.findViewById(R.id.iv_guanzhu);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(fan.get(position).userface, holder.face);
            holder.name.setText(fan.get(position).fusername);
            if (fan.get(position).mutual.equals("0")) {
                holder.iv_guanzhu.setImageDrawable(getResources()
                        .getDrawable(R.drawable.guanzhu_ok));
            }
            if (fan.get(position).mutual.equals("1")) {
                holder.iv_guanzhu.setImageDrawable(getResources().getDrawable(R.drawable.a_b));
            }
            holder.iv_guanzhu.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(MenuAttention.this).setMessage("取消关注")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteGuanZhu(fan.get(position).followuid, position);
                                    dialog.dismiss();
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {}
                            }).create().show();
                }
            });
            return convertView;
        }

    }

    private void deleteGuanZhu(String uid2, final int positon) {
        RequestParams params = new RequestParams();
        params.put("follow_uid", uid2);
        AddClient.get(Address.GUZNZHUDELETE, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    fans.remove(positon);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getApplicationContext(), "取消关注成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    class ViewHolder {
        CircleImageView face;
        ImageView iv_guanzhu;
        TextView name;
    }

    private int page = 1;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_common_cancel:
                finish();
                break;

            default:
                break;
        }
    }
}
